package com.itheima.Controller;


import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.upload-path}")
    private String path;


    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        String fileNName = UUID.randomUUID().toString();

        String suffix = ".jpg";
        String originalFilename = file.getOriginalFilename();
        if(originalFilename!=null){
            suffix = originalFilename.substring(originalFilename.indexOf("."));
        }
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        file.transferTo(new File(path+fileNName+suffix));
        return R.success(fileNName+suffix);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse hsr) throws IOException {
        FileInputStream fis = new FileInputStream(new File(path + name));
        ServletOutputStream sos = hsr.getOutputStream();
        byte[] bytes = new byte[10240];
        while (fis.read(bytes)!=-1){
            sos.write(bytes);
        }
        fis.close();
        sos.close();
    }


}




